
#include <BStyle>
#include <BPainter>
#include <BRender>
#include <BViewer>
#include <BScene>
#include <BCone>
#include <BCube>
#include <BImage>
#include <BMaterial>
#include <BReadWrite>

#include "ConearHandler.h"

ConearHandler::ConearHandler()
{
	_lengthText = new BTextual();
	_lengthText->setColor(200, 0, 0);
	_lengthText->setCullback(false);
	_lengthText->setLighting(false);
	_lengthText->setPolyMode(Poly_Fill);
	_lengthText->setGlyphSize((BReal)0.3);

	_nodeA = new BBody("nodeA");
	{
		BCube* cube = new BCube(4, 12);
		cube->setColor(100, 200, 255);
		_nodeA->insertShape(cube);
		_nodeA->setMass(100);
	}

	_nodeB = new BBody("nodeB");
	{
		BCone* cone = new BCone(0.5, 2, 24, 10);
		cone->setColor(200, 100, 0);
		_nodeB->insertShape(cone);
		_nodeB->setMass(1);
	}

	BVector pointA = _nodeA->space().max() + BVector(1, 0, 0);
	BVector axisA(1, 0, 0);
	BVector pointB(0, 0, -1);
	BVector axisB(0, 0, 1);
	_restraint = new BConearRestraint(_nodeA, pointA, _nodeB, pointB);
	_restraint->setAxisA(axisA);
	_restraint->setAxisB(axisB);
	_restraint->setColliding(false);
	_restraint->setName("Conear");
	//_restraint->setTwistSpan(1);
	//_restraint->setSwingSpan1(2);
	//_restraint->setSwingSpan2(3);
}
ConearHandler::~ConearHandler()
{

}

void ConearHandler::attached(BViewer* viewer)
{
	BScene* dscene = viewer->scene();
	_nodeA->setPosition(0, 0, 5);
	_nodeB->setPosition(2, 2, 5);
	dscene->insert(_nodeA);
	dscene->insert(_nodeB);
	dscene->insert(_restraint);
	_lengthText->setFont((BFont*)viewer->realFont());
	viewer->scene()->insert(_lengthText);
	this->emit("edit-restraint", _restraint);
}
void ConearHandler::detached(BViewer* viewer)
{
	BScene* dscene = viewer->scene();
	dscene->remove(_nodeA);
	dscene->remove(_nodeB);
	dscene->remove(_restraint);
	viewer->scene()->remove(_lengthText);
}

void ConearHandler::paint(BPainter& painter)
{
	BViewer* viewer = this->viewer();
}
void ConearHandler::render(BRender& render)
{
	render.setLighting(false);
	render.setDepthTest(false);
	render.setLineSmooth(true);
	render.setLineWidth(1);

	BNode* nodeA = _restraint->bodyA();
	BNode* nodeB = _restraint->bodyB();
	const BMatrix& matrixA = nodeA->matrix();
	const BMatrix& matrixB = nodeB->matrix();

	BVector pointA = matrixA * _restraint->pivotA();
	render.setColor(0, 200, 0);
	render.drawLine(pointA, pointA + _restraint->swingAxis());

	render.setColor(200, 0, 0);
	render.drawLine(pointA, pointA + _restraint->horAxis());
	render.setColor(0, 200, 0);
	render.drawLine(pointA, pointA + _restraint->verAxis());

	BVector pointB = matrixB * _restraint->pivotB();
	render.setColor(200, 0, 0);
	render.drawLine(pointB, pointB + _restraint->twistAxis());
}

void ConearHandler::styleEvent(const BEvent& event)
{
	BHandler::styleEvent(event);
	const BStyle* style = event.value();
	BImage* image = style->image("cone-texture");
	if (BShape* shape = _nodeB->shape(0))
	{
		shape->setTexture(image);
	}
}
